package linearstructure.stack.calculator;

import linearstructure.stack.arraystack.ArrayStack;

/**
 * @ author : HyoJoo-W
 * @ createDate : 2021-05-27 21:00
 * @ Description : 中缀表达式计算器(两位数)
 */
public class Calculator
{
    public static void main(String[] args)
    {
        String expr = "30+20*6-2";

        ArrayStack opdStack = new ArrayStack(10);
        ArrayStack oprStack = new ArrayStack(10);

        int index = 0;
        int opd1 = 0;
        int opd2 = 0;
        int opr = 0;
        int res = 0;
        char ch = ' ';
        String keepNum = "";//处理多位数

        do
        {
            ch = expr.substring(index, index + 1).charAt(0);
            if (oprStack.isOpr(ch))
            {
                if (oprStack.isEmpty())
                {
                    oprStack.push(ch);
                }
                else
                {
                    if (oprStack.getPriority(ch) <= oprStack.getPriority(oprStack.getTop()))
                    {
                        opd1 = opdStack.pop();
                        opd2 = opdStack.pop();
                        opr = oprStack.pop();
                        res = opdStack.cal(opd1, opd2, opr);

                        opdStack.push(res);

                    }
                    oprStack.push(ch);
                }
            }
            else
            {
                //不是操作符
                //opdStack.push(ch - 48);
                keepNum += ch;
                if (index == expr.length() - 1)
                {
                    //已经到达最后一个字符
                    opdStack.push(Integer.parseInt(keepNum));
                }
                else
                {
                    if (oprStack.isOpr(expr.substring(index + 1, index + 2).charAt(0)))
                    {
                        //后一位是运算符
                        opdStack.push(Integer.parseInt(keepNum));
                        keepNum = "";
                    }
                }

            }
            index++;
        } while (index < expr.length());

        while (!oprStack.isEmpty())
        {
            opd1 = opdStack.pop();
            opd2 = opdStack.pop();
            opr = oprStack.pop();
            res = opdStack.cal(opd1, opd2, opr);

            opdStack.push(res);
        }
        System.out.println("结果为:" + opdStack.pop());
    }

}
